#!/usr/bin/env python3
# -*- coding utf-8 -*-
# author:hu tongwang
# module_name:semaphore_api
#########################
from ansible.module_utils.basic import *
import requests
import json


def runTask(api_ip, api_port, user, password, project, template_id):
    status = 0
    output = ""
    url = "http://{}:{}/api/auth/login".format(api_ip,api_port)

    payload = json.dumps({
        "auth": user,
        "password": password
    })
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    response.close()

    if response.status_code != 204:
        print("登录失败，请检查用户名和密码.... ")
        output = "登录失败，请检查用户名和密码.... "
    else:
        # print(response.cookies.get("semaphore"),type(response.cookies.get("semaphore")))
        # url = "http://192.168.0.103:3000/api/project/1/tasks"
        url = "http://{}:{}/api/project/{}/tasks".format(
            api_ip,
            api_port,
            project)
        print("url",url)
        payload = json.dumps({
            "template_id": template_id
        })
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Cookie': "semaphore=" + response.cookies.get("semaphore")
        }
        response2 = requests.request(
            "POST", url, headers=headers, data=payload)
        output = response2.text
        if response2.ok :
            status = 0
        else:
            status = 1
        response2.close()
    return status,output  


def main():
    # 初始化一个module实例,传递进去的参数里面指定了name为必填项,用required=True修饰
    module = AnsibleModule(
        argument_spec=dict(
            api_ip=dict(required=True),
            api_port=dict(required=True),
            user=dict(required=True),
            password=dict(required=True,no_log=True),
            project=dict(required=True),
            template_id=dict(required=True,type='int')
        ),
        supports_check_mode=True
    )
    API_IP = module.params['api_ip']
    API_PORT = module.params['api_port']
    USER = module.params['user']
    PASSWORD = module.params['password']
    PROJECT = module.params['project']
    TEMPLATE_ID = module.params['template_id']

    # 根据不同变量,执行任务,输出不同内容
    status, output = runTask(
        API_IP,
        API_PORT,
        USER,
        PASSWORD,
        PROJECT,
        TEMPLATE_ID
    )
    if status == 0:
        result = dict(stdout=output, changed=True, rc=0)
        module.exit_json(**result)
    else:
        result = dict(msg=output, rc=status)
        module.fail_json(**result)


main()
